home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2006 December / PCWDEC06.iso / Software / Trial / Paint Shop Pro XI / Data1.cab / jasctools.py < prev    next >
Encoding:
Text File  |  2006-08-04  |  11.7 KB  |  345 lines

  1. #
  2. #   JascTools.py - Obsolete - Please use PSPTools.py
  3. #
  4. #   Utility functions
  5.  
  6. true = 1
  7. false = 0
  8. MaxLineLength = 85
  9.  
  10. runInPSP = true
  11.  
  12. if runInPSP:
  13.     from PSPApp import *
  14.  
  15. import string
  16. import types
  17.  
  18. # remove newline chars from a string and return the modified string
  19. def stripNewlines(str):
  20.     return string.replace(str, chr(10), " ")
  21.         
  22. # *******************************************************************************
  23. #   Function:    RemoveComments
  24. #   Author:      Steve Neumeyer
  25. #   Purpose:     remove comment markers from some python code
  26. #   Returns:     the updated command string with comments markers removed
  27. #   Parameters:  text - the string containing the code
  28. #   Notes:       
  29. # ********************************************************************************
  30. def RemoveComments(text):
  31.     # deletelist is a list of char positions that we will delete
  32.     deletelist = []
  33.  
  34.     blockSize = len(text)
  35.  
  36.     pos = 0
  37.     # mark the position of all hash marks in the command text for deletion
  38.     while pos < blockSize-1:
  39.         while text[pos] == '#' or text[pos] == ' ' or text[pos] == chr(9):
  40.             if text[pos] == '#':
  41.                 deletelist += [pos]
  42.             pos += 1
  43.  
  44.         while text[pos] != chr(10) and pos < blockSize-1:
  45.             pos += 1
  46.         if text[pos] == chr(10):
  47.             pos += 1
  48.  
  49.     pos = len(deletelist)-1
  50.     # delete the hash marks from the command text
  51.     while pos >= 0:
  52.         delIndex = deletelist[pos]
  53.         cmdText = text
  54.         text = cmdText[:delIndex] + cmdText[delIndex+1:]
  55.         pos -= 1
  56.  
  57.     return text
  58.  
  59. #******************************************************************************
  60. #   Function:    AddComments
  61. #   Author:      Steve Neumeyer
  62. #   Purpose:     comment out some python code
  63. #   Returns:     the updated command string with comments inserted
  64. #   Parameters:  text - the string containing the code to be commented
  65. #   Notes:       
  66. #******************************************************************************
  67. def AddComments(text):
  68.  
  69.     # insert a comment marker at the beginning
  70.     text = '#' + text
  71.  
  72.     insertlist = []
  73.     pos = 0
  74.  
  75.     # if we find a newline char, put its index location into a list
  76.     for x in text:
  77.         if x == chr(10):
  78.             insertlist += [pos]
  79.         pos += 1
  80.  
  81.     blockLen = len(text)
  82.     stringCtr = blockLen
  83.     posCtr = len(insertlist)-1
  84.  
  85.     # cycle backwards thru the block, inserting a '#' at all marked locations
  86.     while posCtr>=0:
  87.         text = text[:insertlist[posCtr]+1] + '#' + text[insertlist[posCtr]+1:]
  88.         posCtr -= 1
  89.  
  90.     return text        
  91.     
  92. def FormatParameterRepository( PR, StartIndentLevel = 4 ):
  93.     ''' apply PSP Style formatting to a parameter repository.
  94.         This means K&R style braces on formatting of a dict,
  95.         with each key on its own line.  List and tuple types
  96.         are word wrapped at column 85, though I have not tried to
  97.         ensure that the word wrap algorithms are identical'''
  98.     CurrentIndent = StartIndentLevel
  99.     OutStr = '{\n'
  100.     CurLine = ' ' * CurrentIndent
  101.     FirstVal = 1
  102.     
  103.     # we assume that the parameter coming in is always a dict
  104.     for key in PR.keys():
  105.         
  106.         # on all keys but the first have to put a comma and newline to advance
  107.         if not FirstVal:
  108.             CurLine += ',\n'
  109.             OutStr += CurLine
  110.             CurLine = ' ' * CurrentIndent
  111.             
  112.         FirstVal = 0
  113.         CurLine += "'" + key + "'"
  114.         CurLine += ': '
  115.         if type(PR[key]) == types.DictionaryType:
  116.             CurLine += FormatParameterRepository( PR[key], CurrentIndent + 4 )
  117.         elif type(PR[key]) == types.ListType:
  118.             CurLine += FormatList( PR[key], CurrentIndent, len(CurLine), '[', ']' )
  119.         elif type(PR[key]) == types.TupleType:
  120.             CurLine += FormatList( PR[key], CurrentIndent, len(CurLine), '(', ')' )
  121.         else:
  122.             CurLine += repr(PR[key])
  123.  
  124.     # put out the last new line and the closing brace
  125.     CurLine += '\n'
  126.     OutStr += CurLine
  127.     CurLine = ' ' * CurrentIndent + '}'
  128.     OutStr += CurLine
  129.     
  130.     return OutStr
  131.  
  132. def FormatList( ListVal, CurrentIndent, CurLineLength, OpenChar, CloseChar ):
  133.     ''' format a list using the same parameters as PSP.
  134.         Values are put out on the same line until we reach out max line
  135.         length, then we start a new line, apply the indent and keep
  136.         going.'''
  137.  
  138.     OutStr = ''
  139.     CurLine = OpenChar
  140.     FirstVal = 1
  141.     
  142.     for Val in ListVal:
  143.         if not FirstVal:
  144.             CurLine += ', '
  145.  
  146.         FirstVal = 0
  147.         
  148.         if len(CurLine) + CurLineLength > MaxLineLength:
  149.             OutStr += CurLine
  150.             CurLine = ' ' * CurrentIndent
  151.             CurLineLength = 0
  152.             
  153.         if type(Val) == types.DictionaryType:
  154.             CurLine += FormatParameterRepository( Val, CurrentIndent + 4 )
  155.         elif type(Val) == types.ListType:
  156.             CurLine += FormatList( Val, CurrentIndent, len(CurLine), '[', ']' )
  157.         elif type(Val) == types.TupleType:
  158.             CurLine += FormatList( Val, CurrentIndent, len(CurLine), '(', ')' )
  159.         else:
  160.             CurLine += repr(Val)
  161.  
  162.     OutStr += CurLine
  163.     OutStr += CloseChar +  ' '
  164.     return OutStr
  165.  
  166. #******************************************************************************
  167. #   Function:    changeExecutionMode
  168. #   Author:      Steve Neumeyer
  169. #   Purpose:     given a string representing python source for a command,
  170. #                    set the execution mode specified.
  171. #   Returns:     the updated command string
  172. #   Parameters:  pyStr - python command as a string
  173. #                 exeMode - the new execution mode to set into the python command
  174. #   Notes:       
  175. #******************************************************************************
  176. def changeExecutionMode(pyStr, newExeMode):
  177.    # newMode = 'App.Constants.ExecutionMode.' + newExeMode
  178.     beginIndex = string.find(pyStr, 'ExecutionMode')
  179.     beginIndex += len('ExecutionMode')
  180.     beginIndex += 3 # skip over the ' : and <space> chars
  181.     endIndex = string.find(pyStr[beginIndex:], ",")
  182.     if endIndex < 0:
  183.         endIndex = string.find(pyStr[beginIndex:], '}')
  184.     pyStr = pyStr[:beginIndex] + 'App.Constants.ExecutionMode.' + newExeMode + pyStr[beginIndex+endIndex:]
  185.     return pyStr
  186.  
  187. # return the execution mode given the command string as python code
  188. def getExecutionMode(pyStr):
  189.     beginIndex = string.find(pyStr, 'ExecutionMode')
  190.     beginIndex += len('ExecutionMode')
  191.     beginIndex += 2 # skip over the ' and : chars
  192.     endIndex = string.find(pyStr[beginIndex:], ",")
  193. #    crIndex = string.find(pyStr[beginIndex:], chr(10))
  194. #    if crIndex < endIndex and crIndex >= 0:
  195. #        endIndex = crIndex
  196.     # its the last entry in GeneralSettings, so terminate with a '}'
  197.     if endIndex < 0: 
  198.         bracketIndex = string.find(pyStr[beginIndex:], '}')
  199.         newlineIndex = string.find(pyStr[beginIndex:], chr(10))
  200.         if bracketIndex < newlineIndex:
  201.             endIndex = bracketIndex
  202.         else:
  203.             endIndex = newlineIndex
  204.     exeMode = string.strip( pyStr[beginIndex:beginIndex+endIndex] )
  205.     temp = string.replace(exeMode, 'App.Constants.ExecutionMode.', '')
  206.     return temp
  207.  
  208. # the App.Edit() extension currently will add quotes around constants
  209. # like so: 'App.Constants.Boolean.True' what we actually want is:
  210. # App.Constants.Boolean.True without the single quote marks
  211. def removeQuotesFromPSPConstants(dictAsString):
  212.     
  213.     start = 0
  214.     constantIdx = string.find(dictAsString, 'App.Constants', start)
  215.  
  216.     # remove trailing quotes
  217.     while constantIdx > -1: # while we have constants
  218.  
  219.         QuoteIdx = string.find(dictAsString, '\'', constantIdx)
  220.         NewlineIdx = string.find(dictAsString, '\n', constantIdx)
  221.         CommaIdx = string.find(dictAsString, ',', constantIdx)
  222.         
  223.         # if we find a ' before a \n or , then there is a quoted constant...
  224.         if (QuoteIdx < NewlineIdx) or (QuoteIdx < CommaIdx):
  225.             # remove the trailing quote
  226.             dictAsString = dictAsString[:QuoteIdx] + dictAsString[QuoteIdx+1:]
  227.             start = QuoteIdx + 1
  228.         else:
  229.             start = constantIdx + 1
  230.         
  231.         # go find the next constant, if any
  232.         constantIdx = string.find(dictAsString, 'App.Constants', start)
  233.         
  234.     # remove the leading quotes
  235.     dictAsString = string.replace(dictAsString, '\'App.Constants', 'App.Constants')
  236.  
  237.     return dictAsString    
  238.     
  239.  
  240. #******************************************************************************
  241. #   Function:    GetQuotedFields
  242. #   Author:      Steve Neumeyer
  243. #   Purpose:     extract quoted strings from the complete text of a command.
  244. #                 store the strings in a list
  245. #   Returns:     a list containing individual script parameters
  246. #   Parameters:  commandtext - the complete text of a script (raw)
  247. #   Notes:       this function will ignore nesting and get everything in quotes
  248. #        ATTENTION: the code assumes that the script generator will only generate one
  249. #            key/value pair per line for each item in a command's dictionary
  250. #******************************************************************************
  251. def GetQuotedFields(commandtext):
  252.     quotepositions = [] # initialize empty list
  253.     result = 0
  254.     
  255.     while (result != -1):
  256.         temp = result
  257.         result = string.find(commandtext, "'", result)
  258.         doubleQuote1 = string.find(commandtext, '"', temp)
  259.         doubleQuote2 = string.find(commandtext, '"', doubleQuote1 + 1)
  260.         escapedQuote = string.find(commandtext, "\\'", temp)
  261.         if escapedQuote != -1:
  262.             escapedQuote += 1
  263.  
  264.         # get the location of the last quote mark in the current line,
  265.         # this will be used to ensure there is not a false match when
  266.         # detecting an escaped quote as in the following script fragment:
  267.         # 'Folder': 'D:\\',
  268.         lastquoteonline = 0
  269.         if escapedQuote != -1:
  270.             eolposition = string.find(commandtext, '\n', temp)
  271.             lastquoteonline = string.rfind(commandtext, "'", temp, eolposition)        
  272.         
  273.         # add the quote position to the list, but not if its an embedded quote: \'
  274.         if (result != -1):    # if a single quote was found
  275.             if (result != escapedQuote): # if the single quote found was not an escaped quote
  276.                 if (result > doubleQuote1) and (result < doubleQuote2):
  277.                     result = result + 1  # ignore single quote within double quotes
  278.                 else:
  279.                     quotepositions = quotepositions + [result] # add index to list
  280.                     result = result + 1
  281.             # if this block is executed, the parser thinks it found and embedded quote,
  282.             # but that may not actually be the case.
  283.             elif (result == escapedQuote) and (escapedQuote == lastquoteonline):
  284.                 quotepositions = quotepositions + [result] # add index to list
  285.                 result = result + 1
  286.             else:
  287.                 result = result + 1 # ignore that single quote
  288.  
  289.     # this error will get printed if there is not an
  290.     # even number of quotes in the command text
  291.     if (len(quotepositions) % 2 != 0) :
  292.         print 'Quote mark error in the command script'
  293.  
  294.     # now fill up list with command name and attributes
  295.     commandinfo = []
  296.     i = 0
  297.     while ( i<(len(quotepositions)) ) :
  298.         # command component text to the list
  299.         commandinfo = commandinfo + [commandtext[quotepositions[i]+1:quotepositions[i+1]]]
  300.         i = i+2
  301.         
  302.     return commandinfo            
  303.     # test for an even number of quotes here (optional)
  304.  
  305. #******************************************************************************
  306. #   Function:    GetDictFromCmdString
  307. #   Author:      Steve Neumeyer
  308. #   Purpose:     given a string representing a PSP command, return a dictionary
  309. #                 containing the repository attributes for the command
  310. #   Returns:     a list containing individual script parameters
  311. #   Parameters:  commandtext - the complete text of a script (raw)
  312. #   Notes:       this function will ignore nesting and get everything in quotes
  313. #******************************************************************************
  314. def GetDictFromCmdString(cmdstring):
  315.     index2delete = -1
  316.     begindictindex = string.find(cmdstring, '{')
  317.  
  318.     #    dictstring = cmdstring[begindictindex:]
  319.     cmdstring = cmdstring[begindictindex:]
  320.  
  321.     # remove the ')' char at the end of the string
  322.     strlength = len(cmdstring)
  323.     x = strlength-1
  324.     while (x>0):
  325.         if cmdstring[x] == ')':
  326.             index2delete = x
  327.             break
  328.         x -= 1
  329.     if index2delete == -1:
  330.         dictstring = cmdstring
  331.     else:
  332.         dictstring = cmdstring[:index2delete]
  333.  
  334.     return eval(dictstring)
  335.  
  336. def GetPropertiesDict(cmdstring):
  337.     index2delete = -1
  338.     begindictindex = string.find(cmdstring, '{')
  339.  
  340.     cmdstring = cmdstring[begindictindex:]
  341.  
  342.     dictstring = cmdstring
  343.     return eval(dictstring)
  344.     
  345.